package yuan.handler;

import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import yuan.dto.LinkDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * 基础信息获取
 *
 * @Author yuan
 * @Date 2021/6/26 15:24
 */
@Slf4j
@Configuration
public class BaseHandler {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取token
     *
     * @return
     */
    public String getToken() {
        try {
            String url = "http://api.qa.it.shanghai.nyu.edu/api/app/getToken?appKey=clk-test&appSecret=8BRjYoo6UWychyuykX";
            String forObject = restTemplate.getForObject(url, String.class);
            JSONObject object = JSONObject.parseObject(forObject);
            if ("true".equalsIgnoreCase(object.get("success").toString())) {
                return object.get("result").toString();
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return "";
    }

    /**
     * 获取批量下载的链接
     *
     * @return
     */
    public List<LinkDTO> getBatchDownloadLink() {
        try {
            String url = "http://api.qa.it.shanghai.nyu.edu/api/file/batchGetDownloadLink";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("X-Access-Token", getToken());
            Map<String, Object> map = new HashMap<>();
            Set<Long> set = new HashSet<>();
            set.add(84L);
            set.add(88L);
            map.put("fileIdList", set);
            HttpEntity httpEntity = new HttpEntity(map, headers);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
            JSONObject obj = JSONObject.parseObject(responseEntity.getBody());
            if (obj.get("success").toString().toLowerCase() == "true") {
                List<LinkDTO> list = JSONObject.parseArray(obj.get("result").toString(),
                        LinkDTO.class);
                return list;
            }
            return null;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * 下载图片
     *
     * @return
     */
    public void downLoadPhoto(List<LinkDTO> list) {
        try {
            for (LinkDTO linkDTO : list) {
                if ("ok".equalsIgnoreCase(linkDTO.message)) {
                    String url = linkDTO.getLink();
                    String targetPath = "D:\\Java\\springboot-compose\\springboot-resttemplate\\src\\main\\resources\\upload" + File.separator + linkDTO.getFileId() + ".jpg";
                    ResponseEntity<byte[]> forObject = restTemplate.getForEntity(url, byte[].class);
                    Files.write(Paths.get(targetPath), Objects.requireNonNull(forObject.getBody(), "No File"));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 上传图片
     * C:\Users\yuan\Desktop
     *
     * @Author yuan
     * @Date 2021/6/26 18:39
     */
    public String upload(String filePath) {
        try {
            String url = "http://api.qa.it.shanghai.nyu.edu/api/file/upload";
            MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
            FileSystemResource resource = new FileSystemResource(new File(filePath));
            map.add("file", resource);
            map.add("description", "idcard.jpg");
            map.add("fileType", "DOCUMENT");
            map.add("accessControl", "PRIVATE");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            headers.set("X-Access-Token", getToken());
            HttpEntity httpEntity = new HttpEntity(map, headers);
            String result = restTemplate.postForObject(url, httpEntity, String.class);
            JSONObject object = JSONObject.parseObject(result);
            if (object.get("success").toString().toLowerCase() == "true") {
                JSONObject obj = JSONObject.parseObject(object.get("result").toString());
                String fileId = obj.get("fileId").toString();
                System.out.println("fileId:" + fileId);
                return fileId;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return "";
    }

}
